package com.ecnu.web.controller.project;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ecnu.common.core.controller.BaseController;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.entity.SysUser;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectStageMission;
import com.ecnu.system.domain.ProjectUserEvaluate;
import com.ecnu.system.domain.dto.EvaluateDTO;
import com.ecnu.system.domain.dto.EvaluateListDTO;
import com.ecnu.system.domain.dto.ProjectCheckDTO;
import com.ecnu.system.domain.vo.EvaluateVO;
import com.ecnu.system.domain.vo.EvaluatesVO;
import com.ecnu.system.domain.vo.ProjectStageMissionVO;
import com.ecnu.system.domain.vo.StageVO;
import com.ecnu.system.service.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mchange.lang.LongUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "评价模块")
@RestController
@RequestMapping("/evaluate")
public class EvaluateController extends BaseController {

    @Autowired
    private IProjectUserService projectUserService;
    @Autowired
    private IProjectStageMissionService stageMissionService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IProjectUserEvaluateService projectUserEvaluateService;
    @Autowired
    private IProjectResultService projectResultService;
@Autowired
private ISysUserService sysUserService;

    @PostMapping("/list")
    @ApiOperation(value = "评价列表")
    private TableDataInfo list(@Valid @RequestBody EvaluateListDTO dto) {
        LoginUser loginUser = getLoginUser();
        return projectUserService.selectEvaluateList(dto, loginUser);
    }

    @GetMapping("/projectInfo")
    @ApiOperation(value = "评价第一层概览明细")
    private AjaxResult projectInfo(String userId, String projectId) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        LoginUser loginUser = getLoginUser();
        EvaluateVO evaluateVO = new EvaluateVO();
        //获取项目阶段任务
        List<ProjectStageMissionVO> projectStageMissionVOS =
                stageMissionService.selectEvaluateList(userId, projectId, loginUser);
        if (CollectionUtils.isEmpty(projectStageMissionVOS)) {
            List<StageVO> copy = new ArrayList<>();
            StageVO stageVO = new StageVO();
            stageVO.setId("last");
            stageVO.setMissionName("终评");
//            stageVO.setScore(0);
            copy.add(stageVO);
            evaluateVO.setStageList( copy);
            return AjaxResult.success(evaluateVO);
        }
        List<StageVO> copy = OtherUtil.copy(projectStageMissionVOS, StageVO.class);
        //取分数
        evaluateVO = projectUserEvaluateService.getStageList(projectId, userId,copy);
//        evaluateVO.setStageList(one);
        return AjaxResult.success(evaluateVO);
    }

    @GetMapping("/stageInfo")
    @ApiOperation(value = "评价第二层成果明细")
    private AjaxResult stageInfo(String userId, String stageId) {
        LoginUser loginUser = getLoginUser();

        return stageMissionService.selectStageList(userId, stageId,loginUser);
    }

    @PostMapping("/save")
    @ApiOperation(value = "评价")
    private AjaxResult save(@RequestBody EvaluateDTO dto) {
        LoginUser loginUser = getLoginUser();
        try {
            return projectUserEvaluateService.addEvaluate(dto, loginUser);
        } catch (JsonProcessingException e) {
            logger.error("评价模块保存错误", e.getMessage());
            return AjaxResult.error("保存失败，请联系管理员调整");
        }
//        return AjaxResult.success();
    }

    @GetMapping("/evaluateZip")
    @ApiOperation(value = "下载文件")
    private void get(String userId, String projectId,
                     HttpServletResponse response) {
        LoginUser loginUser = getLoginUser();
        //根据任务和人员id获取到概览列表，概览id列表去对应取任务清单，获取任务清单id
        List<ProjectStageMission> projectStageMissionVOS =
                stageMissionService.selectMissionList(userId, projectId, loginUser);
        Project project = projectService.getById(projectId);
        SysUser sysUser = sysUserService.selectUserById(Long.valueOf(userId));
        if (project == null) {
            throw new RuntimeException("活动不存在");
        }
        if (CollectionUtils.isEmpty(projectStageMissionVOS)) {
           throw new RuntimeException( "没有可导出的概览文件");
        }
        if (sysUser==null) {
            throw new RuntimeException("用户不存在");
        }
        try {
            //获得概览ID数组和任务清单ID数组之后去projectResult表查文件地址
            byte[] zipData = projectResultService.selectFileZip(projectStageMissionVOS,userId,loginUser);

            // 设置响应头
            response.setContentType("application/zip");
            response.setCharacterEncoding("utf-8");

           String encodedFilename = URLEncoder.encode(project.getProName()+"-"+sysUser.getNickName(),
                   StandardCharsets.UTF_8.name()).replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''"+encodedFilename+".zip");

            // 写出 ZIP 数据
            response.getOutputStream().write(zipData);
            response.getOutputStream().flush();
        } catch (Exception e) {
            logger.error("导出 ZIP 文件失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
